package com.lixin.rabbitmq.work.fair;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * work公平分发模式-消费者
 * 多个消费者监听同一个队列
 * broker会根据消费者的消费能力来进行分发消息
 */
public class Consumer implements Runnable {
    @Override
    public void run() {
        Connection connection = null;
        Channel channel = null;
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.3.17");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        try {
            // 创建连接connection
            connection = factory.newConnection("adminConn");
            // 创建通道channel
            channel = connection.createChannel();
            final Channel finalChannel = channel;
            // 监听某个队列，有消息就取出消费掉
            final String threadName = Thread.currentThread().getName();
            // 同一时刻，服务器只会推送一条消息给消费者
            finalChannel.basicQos(1);
            channel.basicConsume(
                    "user", // 要监听的队列
                    false, // 手动应答(公平分发模式)
                    new DeliverCallback() { // 成功从队列中取到消息的回调
                        @Override
                        public void handle(String s, Delivery delivery) throws IOException {
                            if (threadName.equals("work1")) {
                                try {
                                    TimeUnit.SECONDS.sleep(1);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            } else if (threadName.equals("work2")) {
                                try {
                                    TimeUnit.SECONDS.sleep(2);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            System.out.println(threadName + " 接收到的消息是：" + new String(delivery.getBody(), StandardCharsets.UTF_8));
                            // 手动应答
                            finalChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                        }
                    }, new CancelCallback() { // 未能成功从队列中取到消息的回调
                        @Override
                        public void handle(String s) throws IOException {
                            System.out.println("接收消息失败");
                        }
                    });
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
